<template>
  <div class="dialog-container">
    <el-dialog
      v-dialogDrag
      title="LookupItem信息"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @open="onOpen"
      @opened="onOpened"
      @close="onClose"
      @closed="onClosed"
    >
      <div class="form-container">
        <el-form ref="form" v-loading="pageLoading" :model="form" label-position="top" disabled>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="编码" prop="code">
                <el-input v-model="form.code" size="mini" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" size="mini" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-radio-group v-model="form.state" @change="void 0">
                  <el-radio :label="'0'">禁用</el-radio>
                  <el-radio :label="'1'">启用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="2" size="mini" autocomplete="off" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-container" style="padding: 10px 0px 0px 0px;">
        <div class="search-container">
          <el-form ref="conditionForm" :model="searchForm" label-position="top">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="编码">
                  <el-input ref="code" v-model="searchForm.code" size="mini" placeholder="编码" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="名称">
                  <el-input v-model="searchForm.name" size="mini" placeholder="名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="table-container">
          <el-row style="margin-bottom: 10px;">
            <el-button icon="el-icon-search" type="primary" size="mini" @click="onSearch">查询</el-button>
            <el-button icon="el-icon-close" type="danger" size="mini" @click="onClear">清空</el-button>
            <el-button icon="el-icon-plus" type="success" size="mini" @click="onAdd">新增</el-button>
            <el-button icon="el-icon-plus" type="success" size="mini" @click="onCompleted">完成</el-button>
          </el-row>
          <el-form :model="tableForm">
            <el-table
              v-loading="listLoading"
              :data="tableForm.list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              :height="300"
              :stripe="true"
              class="table-editor"
              :row-class-name="rowClassName"
              @row-click="rowClick"
            >
              <el-table-column type="index" width="50" label="序号" align="center" />
              <el-table-column label="编号" prop="code" width="150" class-name="td-editor">
                <template scope="scope">
                  <el-form-item v-if="editor.index === scope.$index" label-width="0px" :prop="'list.' + scope.$index + '.code'" :rules="tableForm.rules.code">
                    <el-input v-model="scope.row.code" v-focus size="small" placeholder="请输入" class="input-editor" />
                  </el-form-item>
                  <span v-else>{{ scope.row.code }}</span>
                </template>
              </el-table-column>
              <el-table-column label="名称" prop="name" width="150" class-name="td-editor">
                <template scope="scope">
                  <el-form-item v-if="editor.index === scope.$index" label-width="0px" size="small" :prop="'list.' + scope.$index + '.name'" :rules="tableForm.rules.name">
                    <el-input v-if="editor.index === scope.$index" v-model="scope.row.name" size="small" placeholder="请输入" class="input-editor" />
                  </el-form-item>
                  <span v-else>{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="state" width="100" class-name="td-editor td-no-validate">
                <template scope="scope">
                  <el-select v-if="editor.index === scope.$index" v-model="scope.row.state" size="small" placeholder="请选择" class="input-editor" @change="stateChange(scope.row, scope.row.state)">
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                  </el-select>
                  <span v-else>{{ scope.row.stateName || scope.row.state === "1" ? "启用" : "禁用" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="顺序" prop="sort" width="100" class-name="td-editor td-no-validate">
                <template scope="scope">
                  <el-input v-if="editor.index === scope.$index" v-model="scope.row.sort" size="small" placeholder="请输入" class="input-editor" />
                  <span v-else>{{ scope.row.sort }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" width="150" show-overflow-tooltip class-name="td-editor td-no-validate">
                <template scope="scope">
                  <el-input v-if="editor.index === scope.$index" v-model="scope.row.remark" size="small" placeholder="请输入" class="input-editor" />
                  <span v-else>{{ scope.row.remark }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建人" prop="createBy" />
              <el-table-column label="创建时间" width="165">
                <template slot-scope="scope">
                  <i class="el-icon-time" />
                  <span>{{ scope.row.createDate && dateFormat(scope.row.createDate) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="修改人" prop="updateBy" />
              <el-table-column label="修改时间" width="165">
                <template slot-scope="scope">
                  <i class="el-icon-time" />
                  <span>{{ scope.row.updateDate && dateFormat(scope.row.updateDate) }}</span>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click.stop="del(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pageVo.currentPage"
            :page-sizes="[15, 50, 100, 500]"
            :page-size="pageVo.pageSize"
            :total="pageVo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  directives: {
    focus: {
      inserted: function(el) {
        el.querySelector('input').focus()
      }
    }
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // ----------------------弹框部分-------------------------
      pageLoading: false,
      dialogFormVisible: false,
      form: {
        id: 0,
        code: '',
        name: '',
        state: '1',
        remark: ''
      },
      searchForm: {},
      // 表格值集
      tableForm: {
        list: [],
        rules: {
          code: [{ required: true, message: '请输入', trigger: 'blur' }],
          name: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        deleteIds: []
      },
      listLoading: false,
      multipleSelection: [],
      calcTableHeight: '500px',
      pageVo: {
        total: 0,
        status: true,
        pageSize: 15,
        currentPage: 1
      },
      editor: {
        states: [],
        index: undefined,
        row: undefined
      }
    }
  },
  created() {},
  mounted() {
  },
  methods: {
    onOpen() {
      this.pageLoading = true
      // 重置表单内容
      this.resetForm()
      // 重置表单验证
      this.resetFields('form')
    },
    resetFields(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields()
      })
    },
    resetForm() {
      this.$nextTick(() => {
        this.form = {
          id: 0,
          code: '',
          name: '',
          state: '1',
          remark: ''
        }
      })
    },
    onOpened() {
      this.form = {
        id: this.rowData.id,
        code: this.rowData.code,
        name: this.rowData.name,
        state: this.rowData.state,
        remark: this.rowData.remark
      }
      this.getData()
      this.pageLoading = false
    },
    onClose() {},
    onClosed() {
      this.$parent.rowData = {}
      this.resetForm()
      this.tableForm.list = []
      this.editor.states = []
      this.editor.index = undefined
      this.editor.row = undefined
      this.searchForm.code = ''
      this.searchForm.name = ''
    },
    onSubmit() {
      const formName = 'form'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveFormdata()
        }
      })
    },
    onAdd() {
      this.tableForm.list.push({
        code: '',
        name: '',
        state: '1',
        sort: 0,
        remark: '',
        _editor_state: 'add'
      })
    },
    onCompleted() {
      const oldRowData = this.editor.row
      const editorIndex = this.editor.index
      const editorRowData = this.tableForm.list[editorIndex]
      // 结束编辑状态
      this.editor.row = undefined
      this.editor.index = undefined
      // 比较数据有没有改变
      var isChange = false
      for (var key in editorRowData) {
        if (editorRowData[key] !== oldRowData[key]) {
          isChange = true
          break
        }
      }
      if (isChange && editorRowData.id) {
        this.tableForm.list[editorIndex]._editor_state = 'change'
      }
    },
    stateChange(row, state) {
      const stateName = state === '1' ? '启用' : '禁用'
      row.stateName = stateName
    },
    del(row, $index) {
      if (this.tableForm.list.length > 0) {
        const deleteRow = this.tableForm.list.splice($index, 1)
        if (deleteRow.id) {
          this.tableForm.deleteIds.push(deleteRow.id)
        }
      }
    },
    saveFormdata() {
      const url = 'system/lookupItem/addSave'
      var itemList = []
      if (this.tableForm.list && this.tableForm.list.length) {
        for (var i = 0; i < this.tableForm.list.length; i++) {
          var row = this.tableForm.list[i]
          itemList.push({
            id: row.id,
            code: row.code,
            name: row.name,
            state: row.state,
            sort: row.sort,
            remark: row.remark,
            parentCode: this.form.code
          })
        }
      }
      var params = {
        itemList: itemList,
        deleteIds: this.tableForm.deleteIds
      }
      this.$store.dispatch(url, params).then((data) => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.dialogFormVisible = false
        this.$parent.onSearch()
      })
    },
    rowClassName({ row, rowIndex }) {
      row._rowIndex = rowIndex
      return 'row-mark-' + row._editor_state
    },
    rowClick(row, column, event) {
      if (this.editor.index === row._rowIndex) {
        return
      }
      if (this.editor.index !== undefined) {
        // 完成编辑
        this.onCompleted()
      }
      this.selectRow = row
      this.editor.index = row._rowIndex
      this.editor.row = JSON.parse(JSON.stringify(row))
    },
    // 查询按钮
    onSearch() {
      this.handleCurrentChange(1)
    },
    // 清空按钮
    onClear() {
      this.searchForm.code = ''
      this.searchForm.name = ''
    },
    // 获取数据
    getData() {
      this.listLoading = true
      const params = {
        ...this.searchForm,
        parentCode: this.form.code,
        pageNum: this.pageVo.currentPage,
        pageSize: this.pageVo.pageSize
      }
      this.$store.dispatch('system/lookupItem/page', params).then((data) => {
        var records = data.records
        this.tableForm.list = records
        this.pageVo.total = data.total
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    dateFormat(date) {
      if (date === undefined) {
        return ''
      }
      return this.$Utils.formatDate(new Date(date))
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.pageVo.currentPage = val
      this.getData()
    },
    // 页数改变事件
    handleSizeChange(val) {
      this.pageVo.pageSize = val
      this.pageVo.currentPage = 1
      this.getData()
    },
    // 多选框触发事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style lang="scss">
.table-editor {
  .td-editor {
    padding: 0px !important;

    div.cell {
      padding: 0px 2px 0px 2px;
    }

    .input-editor input {
      height: 28px;
    }
  }

  .td-no-validate {
    .input-editor {
      margin-bottom: 18px;
    }
  }
}
.row-mark-change td:first-child::before {
  position: absolute;
  content: " ";
  border-top: 10px solid #FF0000;
  border-right: 10px solid transparent;
  top: 0px;
  left: 0px;
}
.row-mark-add td:first-child::before {
  position: absolute;
  content: " ";
  border-top: 10px solid #00FF00;
  border-right: 10px solid transparent;
  top: 0px;
  left: 0px;
}
</style>
